<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">录入数据</el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="fungusPlantList"
      border
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column type="expand">
        <template slot-scope="{row}">
          <el-form label-position="left" class="table-expand">
            <el-form-item label="种植日期">
              <span>{{ row.createDate | dateFilter }}</span>
            </el-form-item>
            <el-form-item label="种植标题">
              <span>{{ row.plantFungusName }}</span>
            </el-form-item>
            <el-form-item label="种植编号">
              <span>{{ row.plantFungusId }}</span>
            </el-form-item>
            <el-form-item label="菌棒数量">
              <span>{{ row.fungusStickNum }}</span>
            </el-form-item>
            <el-form-item label="菌棒来源">
              <span>{{ row.fungusStickSource }}</span>
            </el-form-item>
            <el-form-item label="种植备注">
              <span>{{ row.remark }}</span>
            </el-form-item>
            <el-form-item label="种植图片">
              <el-image
                class="image"
                :src="imgUrl + '/' + row.image"
                :preview-src-list="[imgUrl + '/' + row.image]"
                fit="cover"
              >
                <div slot="error" class="image-slot">
                  <i class="el-icon-picture-outline" />
                </div>
              </el-image>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column label="编号" align="center" width="90px" type="index" :index="indexMethod" />
      <el-table-column label="种植日期" align="center" width="100px">
        <template slot-scope="{row}">
          <span>{{ row.createDate | dateFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="菌棒数量" align="center">
        <template slot-scope="{row}">
          <span>{{ row.fungusStickNum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="菌棒来源" align="center">
        <template slot-scope="{row}">
          <span>{{ row.fungusStickSource }}</span>
        </template>
      </el-table-column>
      <el-table-column label="种植标题" align="center" :show-overflow-tooltip="true">
        <template slot-scope="{row}">
          <span>{{ row.plantFungusName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="种植备注" align="center" :show-overflow-tooltip="true">
        <template slot-scope="{row}">
          <span>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        min-width="100px"
        class-name="small-padding fixed-width"
        width="100px"
      >
        <template slot-scope="{row}">
          <el-button type="danger" size="mini" @click="handleDelete(row.plantFungusId)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-el-drag-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="100px"
      >
        <el-form-item label="菌类品种" prop="fungusTypeId">
          <el-select
            v-model="temp.fungusTypeId"
            class="select"
            placeholder="请选择"
            :disabled="fungusTypeFlag"
            @change="handleFungusTypeChange"
          >
            <el-option
              v-for="item in fungusTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="菌棒数量" prop="fungusStickNum">
          <el-input-number
            v-model="temp.fungusStickNum"
            class="select"
            controls-position="right"
            :min="1"
          />
        </el-form-item>
        <el-form-item label="菌棒来源" prop="fungusStickSource">
          <el-input v-model="temp.fungusStickSource" />
        </el-form-item>
        <!-- <el-form-item label="所在基地" prop="siteId">
          <el-select
            v-model="temp.siteId"
            class="select"
            placeholder="请选择"
            :disabled="siteFlag"
            @change="handelSiteSelectChange"
          >
            <el-option
              v-for="item in siteOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所在地块" prop="placeId">
          <el-select
            v-model="temp.placeId"
            class="select"
            placeholder="请选择"
            :disabled="placeFlag"
          >
            <el-option
              v-for="item in placeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item> -->
        <el-form-item label="所在基地">
          <el-input v-model="siteName" :disabled="true" />
        </el-form-item>
        <el-form-item label="所在地块">
          <el-input v-model="placeName" :disabled="true" />
        </el-form-item>
        <el-form-item label="种植备注" prop="remark">
          <el-input v-model="temp.remark" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" />
        </el-form-item>
        <el-form-item label="种植日期" prop="createDate">
          <el-date-picker
            v-model="temp.createDate"
            format="yyyy年MM月dd日"
            value-format="yyyy-MM-dd"
            class="select"
            align="right"
            type="date"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="种植图片" prop="image">
          <el-upload
            ref="uploadImage"
            :action="uploadFileUrl"
            name="file"
            :data="data"
            :auto-upload="false"
            list-type="picture-card"
            :limit="1"
            :on-success="handleSuccess"
            :on-preview="handlePictureCardPreview"
            :on-exceed="handleExceed"
            :on-change="handleChange"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus" />
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          :disabled="fungusTypeFlag || siteFlag || placeFlag"
          @click="dialogStatus==='add'?addData():modifiedData()"
        >确定
        </el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { queryFungusPlant, deleteFungusPlant, addFungusPlant } from '@/api/fungusPlant'
import { queryFungusType } from '@/api/fungusType'
import { getSingleBase } from '@/api/base'
import { queryPlace } from '@/api/place'
import elDragDialog from '@/directive/el-drag-dialog'
import { parseTime, formatNumber, codeDate, dateToString } from '@/utils'
import store from '@/store'
import { fungusMixin } from '@/mixins/fungusMixin'

export default {
  name: 'FungusPlant',
  directives: { elDragDialog },
  filters: {
    dateFilter(date) {
      return date.substring(0, 11)
    }
  },
  mixins: [fungusMixin],
  data() {
    const IMAGE_FILE_NAME = 'plantFungusImage'

    return {
      category: 'fungus_plant',
      tableKey: 0,
      fungusPlantList: [],
      listLoading: true,
      listQuery: {
        plantFungusId: '',
        fungusTypeId: -1,
        siteId: -1,
        placeId: -1,
        account: store.getters.token
      },
      fungusTypeQueryList: {
        fungusTypeId: -1,
        account: store.getters.token
      },
      siteQueryList: {
        account: store.getters.token
      },
      placeQueryList: {
        placeId: -1,
        siteId: -1,
        limit: -1,
        pageNumber: 0,
        type: ''
      },
      fungusTypeOptions: [],
      siteOptions: [],
      placeOptions: [],
      data: { // 上传图片的参数
        account: store.getters.token,
        path: IMAGE_FILE_NAME
      },
      temp: {
        plantFungusId: '',
        plantFungusName: '',
        fungusTypeId: null,
        fungusStickNum: 1,
        fungusStickSource: '',
        siteId: null,
        placeId: null,
        remark: '',
        createDate: parseTime(new Date(), '{y}-{m}-{d}'),
        dateCode: '',
        image: '',
        account: store.getters.token
      },
      siteName: '',
      placeName: '',
      rules: {
        fungusTypeId: [
          {
            type: 'number',
            required: true,
            message: '请选择菌类品种',
            trigger: 'change'
          }
        ],
        fungusStickSource: [
          {
            type: 'string',
            required: true,
            message: '请填写菌棒来源',
            trigger: 'change'
          }
        ],
        fungusStickNum: [
          {
            type: 'number',
            required: true,
            message: '请填写菌棒数量',
            trigger: 'change'
          }
        ],
        siteId: [
          {
            type: 'number',
            required: true,
            message: '请选择种植所在基地',
            trigger: 'change'
          }
        ],
        placeId: [
          {
            type: 'number',
            required: true,
            message: '请选择种植所在地块',
            trigger: 'change'
          }
        ],
        remark: [
          {
            type: 'string',
            required: true,
            message: '请填写种植备注',
            trigger: 'change'
          }
        ],
        createDate: [
          {
            type: 'string',
            required: true,
            message: '请选择种植日期',
            trigger: 'change'
          }
        ],
        image: [
          {
            type: 'string',
            required: true,
            message: '请选择种植图片',
            trigger: 'change'
          }
        ]
      },
      dialogStatus: '',
      dialogFormVisible: false,
      dialogVisible: false,
      dialogImageUrl: '',
      textMap: {
        add: '录入数据'
      },
      imgUrl: process.env.VUE_APP_BASE_IMAGE_API + IMAGE_FILE_NAME,
      uploadFileUrl: store.getters.uploadFileUrl
    }
  },
  computed: {
    plantFungusId() {
      const temp = this.temp
      return formatNumber(temp.siteId) + formatNumber(temp.placeId) + codeDate(temp.createDate) + formatNumber(temp.fungusTypeId)
    },
    plantFungusName() {
      const temp = this.temp
      // const site = this.siteOptions.find(item => {
      //   return item.value === temp.siteId
      // })
      // const place = this.placeOptions.find(item => {
      //   return item.value === temp.placeId
      // })
      const fungusType = this.fungusTypeOptions.find(item => {
        return item.value === temp.fungusTypeId
      })
      return dateToString(temp.createDate) + this.siteName + this.placeName + fungusType.label + '种植'
    },
    fungusTypeFlag() {
      return this.temp.fungusTypeId === -1
    },
    siteFlag() {
      return this.temp.siteId === null
    },
    placeFlag() {
      return this.temp.placeId === null
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleFungusTypeChange(fungusTypeId) {
      const fungusType = this.fungusTypeOptions.find(item => {
        return item.value === fungusTypeId
      })
      this.temp.siteId = fungusType.siteId
      this.temp.placeId = fungusType.placeId
      this.getSite(fungusType.siteId)
      this.getPlace(fungusType.placeId)
    },
    getSite(siteId) {
      getSingleBase({ siteId })
        .then(res => {
          console.log(res)
          this.temp.siteId = res.site.siteId
          this.siteName = res.site.siteName
        })
        .catch(err => {
          console.log(err)
        })
    },
    getPlace(placeId) {
      this.placeQueryList.placeId = placeId
      queryPlace(this.placeQueryList)
        .then(res => {
          console.log(res)
          this.temp.placeId = res.places[0].placeId
          this.placeName = res.places[0].placeName
        })
        .catch(err => {
          console.log(err)
        })
    },
    handelSiteSelectChange(siteId) {
      this.getPlace(siteId)
    },
    resetTemp() {
      this.temp = {
        plantFungusId: '',
        plantFungusName: '',
        fungusTypeId: null,
        fungusStickNum: 1,
        fungusStickSource: '',
        siteId: null,
        placeId: null,
        remark: '',
        createDate: parseTime(new Date(), '{y}-{m}-{d}'),
        dateCode: '',
        image: '',
        account: store.getters.token
      }
      this.siteName = ''
      this.placeName = ''
    },
    handleAdd() {
      this.resetTemp()
      this.dialogStatus = 'add'
      this.dialogFormVisible = true
      // this.getFungusType()
      // this.getSite()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    addData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.$refs['uploadImage'].submit()
        }
      })
    },
    handleDelete(id) {
      this.$msgbox
        .confirm('您确定要删除这条数据吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          deleteFungusPlant({ plantFungusId: id })
            .then(response => {
              const index = this.fungusPlantList.findIndex(
                v => v.plantFungusId === id
              )
              this.fungusPlantList.splice(index, 1)
              this.$notify({
                title: '提示',
                message: '删除成功！',
                type: 'success',
                duration: 2000
              })
            })
            .catch(error => {
              console.log(error)
              this.$notify({
                title: '提示',
                message: '删除失败！',
                type: 'error',
                duration: 2000
              })
            })
        })
    },
    handleSuccess(response, file, fileList) {
      fileList.pop()
      this.temp.image = response.fileName
      this.temp.plantFungusId = this.plantFungusId
      this.temp.plantFungusName = this.plantFungusName
      this.temp.dateCode = codeDate(this.temp.createDate)
      addFungusPlant(this.temp).then(response => {
        this.fungusPlantList.unshift(this.temp)
        this.dialogFormVisible = false
        this.$notify({
          title: '提示',
          message: '添加成功！',
          type: 'success',
          duration: 2000
        })
      })
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleChange(file, fileList) {
      if (this.temp.image === '') {
        this.temp.image = 'hasImage'
      }
    },
    handleRemove(file, fileList) {
      if (fileList.length === 0) {
        this.temp.image = ''
      }
    },
    handleExceed(file) {
      this.$message({
        message: '当前版本只支持上传一张图片！',
        type: 'warning'
      })
    },
    indexMethod(index) {
      return index + 1
    }
  }
}
</script>

<style scoped>
.select {
  width:100%;
}

.image {
  width: 250px;
  height: 200px;
  border-radius: 5px;
  background-color: rgb(235,235,235);
  display:flex;
  justify-content: center;
  align-items: center;
}
</style>
